package com.culturalCenter.dataCenter.Utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 配置文件工具类
 *
 * @author
 * @date
 */
@Slf4j
public class PropertiesUtils {

    /**
     * 读取json文件，返回json字符串
     *
     * @param fileName
     *
     * @return
     */
    public static String readJsonFile(String fileName) {
        FileReader fileReader = null;
        Reader reader = null;
        try {
            File jsonFile = ResourceUtils.getFile("classpath:" + fileName);
            fileReader = new FileReader(jsonFile);
            reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            int ch;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            return sb.toString();
        } catch (IOException e) {
            log.error("读取文件报错", e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    public static <T> T parseObjectFromJsonFile(String jsonFilePath, Class<T> cls) throws IOException {

        InputStream inputStream = PropertiesUtils.class.getResourceAsStream(jsonFilePath);

        if (null == inputStream) {
            return null;
        }
        String jsontext = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

        return JSON.parseObject(jsontext, cls);
    }

    public static <T> List<T> parseArrayFromJsonFile(String jsonFilePath, Class<T> cls) throws IOException {

        InputStream inputStream = PropertiesUtils.class.getResourceAsStream(jsonFilePath);
        if (null == inputStream) {
            return null;
        }
        String jsontext = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

        return JSON.parseArray(jsontext, cls);
    }

}
